<?php
// @formatter:off
/**
 * @file c.edit-POOL.php
 * @author Alejandro Dario Simi
 * @date $Date: 2013-06-04 03:02:53 +0000 (Tue, 04 Jun 2013) $
 *
 * $Id: c.edit-POOL.php 68 2013-06-04 03:02:53Z daemonraco@gmail.com $
 * $URL: http://wcomix.googlecode.com/svn/tags/wcomix-1.0.0.1/extensions/TagsRelator/controlers/c.edit-POOL.php $
 */
// @formatter:on

global $wcTagsHolder;

switch($_POST["EDITACTION"]) {
	case "ADD":
		$newTagNames = array();
		foreach(explode(",",$_POST["ACTION_TAGS"]) as $tagName) {
			$tagName = trim($tagName);
			if($tagName) {
				$newTagNames[] = $tagName;
			}
		}

		$newTags = array();
		$currentIds = array_keys($wcRuleAction->tags());
		foreach($newTagNames as $name) {
			//
			// Loading tag.
			$tag = $wcTagsHolder->itemByName($name, $wcGroup);
			//
			// If it is a new tag it creates it.
			if(!$tag) {
				$wcTagsHolder->create($name, $wcGroup);
				$tag = $wcTagsHolder->itemByName($name, $wcGroup);
			}
			//
			// If the tag has no issues and its not on the current list, it is added.
			if($tag && $tag->ok() && !in_array($tag->id, $currentIds)) {
				$newTags[$tag->id] = $tag;
			}
		}

		$stmt = null;
		$stmtId = __CLASS__."::".__FUNCTION__."[POOL-ADD]";
		if($db->has($stmtId)) {
			$stmt = $db->get($stmtId);
		} else {
			$query = "insert\n";
			$query .= "        into {$dbprefix}acts_tare (\n";
			$query .= "                act_rule, act_group, act_action, act_tag, act_also)\n";
			$query .= "        values (:rule, :group, :action, :tag, 0)\n";

			$stmt = $db->prepare($stmtId, $query);
		}

		foreach($newTags as $tag) {
			$params = array(
				":rule" => $wcRule->id(),
				":group" => $wcGroup->id,
				":action" => $wcRuleAction->id(),
				":tag" => $tag->id
			);

			$stmt->execute($params);
		}

		$wcRuleAction->reload();

		break;
	case "REMOVE":
		$tagIds = array();
		foreach($_POST as $name => $value) {
			if(substr($name, 0, 4) == "TAG_") {
				$tagIds[] = substr($name, 4);
			}
		}

		$badTags = array();
		$currentIds = array_keys($wcRuleAction->tags());
		foreach($tagIds as $id) {
			$tag = $wcTagsHolder->item($id, $wcGroup);
			if($tag->ok() && in_array($tag->id, $currentIds)) {
				$badTags[$tag->id] = $tag;
			}
		}

		$stmt = null;
		$stmtId = __CLASS__."::".__FUNCTION__."[POOL-REMOVE]";
		if($db->has($stmtId)) {
			$stmt = $db->get($stmtId);
		} else {
			$query = "delete from {$dbprefix}acts_tare\n";
			$query .= "where       act_rule   = :rule\n";
			$query .= " and        act_group  = :group\n";
			$query .= " and        act_action = :action\n";
			$query .= " and        act_tag    = :tag\n";
			$query .= " and        act_also   = 0\n";

			$stmt = $db->prepare($stmtId, $query);
		}

		foreach($badTags as $tag) {
			$params = array(
				":rule" => $wcRule->id(),
				":group" => $wcGroup->id,
				":action" => $wcRuleAction->id(),
				":tag" => $tag->id,
			);

			$stmt->execute($params);
		}

		$wcRuleAction->reload();

		break;
	default:
		break;
}
?>